package org.bp.spider.util;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

/**
 * @author baiping
 * @version 1.0
 * @date 2017/9/6
 */
public class StreamUtils {
    public static long copyStream(InputStream input, OutputStream output, int offset, int len) throws IOException {
        byte[] buffer = new byte[4096];
        long count = 0L;
        int n1;
        for (; -1 != (n1 = input.read(buffer, offset, len)); count += (long) n1) {
            output.write(buffer, offset, len);
        }

        return count;
    }

    public static long copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[4096];
        long count = 0L;

        int n1;
        for (; -1 != (n1 = input.read(buffer)); count += (long) n1) {
            output.write(buffer, 0, n1);
        }

        return count;
    }

    public static void close(Closeable... closeables) {
        if (CollectionsUtils.isNotAbsEmpty(closeables)) {
            for (Closeable closeable : closeables) {
                if (closeable != null) {
                    try {
                    	if(closeable instanceof OutputStream){
                    		((OutputStream) closeable).flush();
                    	}
                    	if(closeable instanceof Writer){
                    		((Writer) closeable).flush();
                    	}
                        closeable.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void close(AutoCloseable... closeables) {
        if (CollectionsUtils.isNotAbsEmpty(closeables)) {
            for (AutoCloseable closeable : closeables) {
                if (closeable != null) {
                    try {
                        closeable.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
